package com.archie.xunji.guangchang.fragments;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.archie.xunji.R;
import com.archie.xunji.guangchang.adapters.GuangchangAdapter;
import com.archie.xunji.guangchang.entity.GuangchangData;
import com.archie.xunji.guangchang.widgets.SpacesItemDecoration;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class GuangchangFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private String path = "http://service.xunjimap.com/xunjiservice/common1_0_4/index?53D2CFEB65F6BBEEEB42836FE18E7E0D";
    private RecyclerView recyclerView;
    private SwipeRefreshLayout layout;
    private List<GuangchangData> datas;
    private GuangchangAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_guangchang, container, false);
        layout= (SwipeRefreshLayout) v.findViewById(R.id.swiperefreshlayout);
        layout.setOnRefreshListener(this);
        recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new SpacesItemDecoration(5));
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        datas = new ArrayList<GuangchangData>();

        adapter = new GuangchangAdapter(getActivity(), datas);

        recyclerView.setAdapter(adapter);
        postrequest(path);
    }

    private void postrequest(String path) {
        RequestParams params = new RequestParams();
        // params.addHeader("name", "value");
        //  params.addQueryStringParameter("name", "value");

        params.addBodyParameter("userinfoid", "26099");
        params.addBodyParameter("appuserid", "43480");
        params.addBodyParameter("t", "20151110102609");
        params.addBodyParameter("token", "074FD831C183689BFACBD215118EEA525773DC8F");
        params.addBodyParameter("sid", "kJMOzgjVcH");
        params.addBodyParameter("imei", "9692B6993494E9324B7F9560912242B7");
        params.addBodyParameter("os", "Android+4.4.4");
        params.addBodyParameter("key", "WANDOUJIA");

// 只包含字符串参数时默认使用BodyParamsEntity，
// 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
        //  params.addBodyParameter("name", "value");

// 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
// 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
// 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
// MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
// 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
        //   params.addBodyParameter("file", new File("path"));

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                path,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        // testTextView.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            //  testTextView.setText("upload: " + current + "/" + total);
                        } else {
                            // testTextView.setText("reply: " + current + "/" + total);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        List<GuangchangData>list=new ArrayList<GuangchangData>();
                        JSONObject json= null;
                        try {
                            json = new JSONObject(responseInfo.result);
                            JSONObject obj=json.getJSONObject("result");
                            JSONArray array=obj.getJSONArray("data");
                            for(int i=0;i<array.length();i++){
                                GuangchangData data=new GuangchangData();
                                data.parseJSON(array.getJSONObject(i));
                                list.add(data);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        datas.clear();
                        datas.addAll(list);
                        adapter.notifyDataSetChanged();
                        layout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        //  testTextView.setText(error.getExceptionCode() + ":" + msg);
                    }
                });


    }

    @Override
    public void onRefresh() {
        postrequest(path);
    }
}